/* eslint-disable react-hooks/rules-of-hooks */
import React from "react";
import { Button, Form, Input, Toast } from "antd-mobile";
import { getCodeApi, getLoginApi } from "../../api/use";
import { useCountDown, useFd } from "../../hook";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setinfo } from "../../store/slice/userSlice";

function login() {
  const [form] = Form.useForm();
  const fd=useFd()
  const {count,start,isDown}=useCountDown()
  const sendCode = async () => {
    try {
      const result = await form.validateFields(["tel"]);
      const { data: res } = await getLoginApi(result.tel);
      form.setFieldValue("telCode", res.telCode);
      start()
    } catch {
      Toast.show("手机号格式不正确");
    }
  };
  let nav=useNavigate()
  let diapatch=useDispatch()
  const onFinish=async(values)=>{
    const {data:res}=await getCodeApi(values)
    diapatch(setinfo(res))
    nav('/')
  }
  return (
    <div>
      <Form
        form={form}
        onFinish={fd(onFinish)}
        layout="horizontal"
        mode="card"
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Item
          label="手机号"
          name="tel"
          rules={[
            { required: true, message: "手机号不能为空" },
            { pattern: /^1[3-9]\d{9}$/, message: "手机号为11为号码" },
          ]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          label="短信验证码"
          name="telCode"
          extra={<Button onClick={sendCode} disabled={isDown}>{isDown?count+'后可重发':'发送验证码'}</Button>}
          rules={[{ required: true, message: "验证码不能为空" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
      </Form>
    </div>
  );
}

export default login;
